package com.better.common.amqp.config;

import com.better.common.amqp.receiver.UsermodelMessageListenter;
import com.better.common.amqp.util.MQBusinessConstants;
import com.better.common.amqp.util.MQConstants;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 业务相关 RabbitMQ交换机、队列的配置类.定义交换机、key、queue并做好绑定。
 * Created by Administrator on 2018/1/10.
 */
/*@Configuration
@ComponentScan*/
public class BusQueueConfig {
    /**
     * 业务交换机
     */
    @Bean
    public DirectExchange businessExchange() {
        return new DirectExchange(MQBusinessConstants.BUSINESS_EXCHANGE);
    }

    //========================== 声明队列 ===========================

    /**
     * 业务队列,并绑定一个死信队列
     */
    @Bean
    public Queue busQueue() {
        Map<String, Object> arguments = new HashMap<String, Object>();
        /**配置的死信队列*/
        arguments.put("x-dead-letter-exchange", MQConstants.DLX_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", MQConstants.DLX_ROUTING_KEY);
     /*   *//**消息被确认前的最大等待时间*//*
        arguments.put("x-message-ttl", 60000);
        *//**消息队列的最大大长度*//*
        arguments.put("x-max-length", 300);*/
        return new Queue(MQBusinessConstants.BUS_QUEUE,true, false, false,arguments);
    }

    /**
     * 通过死信路由key绑定死信交换机和死信队列
     */
    @Bean
    public Binding busBinding() {
        return BindingBuilder.bind(busQueue()).to(businessExchange())
                .with(MQBusinessConstants.BUS_ROUTING_KEY);
    }

    /**
     * 业务队列的监听
     *
     * @param connectionFactory             RabbitMQ连接工厂
     * @param bussesLetterListenerContainer 业务的监听者
     * @return 监听容器对象
     */
    @Bean
    public SimpleMessageListenerContainer bussesLetterListenerContainer(ConnectionFactory connectionFactory,
                                                                        UsermodelMessageListenter usermodelMessageListenter) {

        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(busQueue());
        container.setExposeListenerChannel(true);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setMessageListener(usermodelMessageListenter);
        /** 设置消费者能处理消息的最大个数 */
        container.setPrefetchCount(100);
        return container;
    }

}
